#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@file:updateapi.py
@time:2017/7/10 0010 15:51
"""
from fabric.colors import *
from fabric.api import *
import os
import time
env.testserver = ['10.10.9.226']
env.uatserver = []
env.formalserver = []

def differentEnv():
    mesg = {}
    if env.host in env.testserver:
        server_code_dir = '/opt/workspace/website'  # 项目路径可以从数据库中读取，这里是写死的。
        stop_tomcat_cmd = "ps aux | grep ClassLoaderLogManager | egrep -v 'grep|datamall' |awk '{print $2}' | xargs kill"
        start_tomcat_cmd = ". /etc/profile && /opt/workspace/tomcat/apache-tomcat-7.0.57/bin/startup.sh"
        rootDirectory = '/opt/workspace/website/datatangapi-service/WEB-INF/classes/'
        mesg['server_code_dir']=server_code_dir
        mesg['stop_tomcat_cmd']=stop_tomcat_cmd
        mesg['start_tomcat_cmd']=start_tomcat_cmd
        mesg['rootDdir'] = rootDirectory

    elif env.host in env.uatserver:
        pass
    elif env.host in env.formalserver:
        pass
    else:
        print('can not loaction the server!')

    return mesg
def codeBackup( server_code_dir,backupTime):
    print(yellow('start backup old code'))
    with cd(server_code_dir):
        run("cp -r datatangapi-service datatangapi-service_%s_bak" % backupTime)

def updateCode(updatePackage):
    n=0
    msg = differentEnv()
    server_code_dir = msg['server_code_dir']
    rootDir = msg['rootDdir']
    codetime = os.path.basename(updatePackage)
    codeBackup(server_code_dir,codetime)
    with open(os.path.join(updatePackage,'list.txt') ) as f:
        for i in f.readlines():
            completeList = os.path.join(rootDir,i.replace('\\','/').strip())
            remoteDir , updateFile = os.path.split(completeList)
            for currentDir, nextDir, currentFileList in os.walk(updatePackage):
                if updateFile in currentFileList:
                    currentFile = os.path.join(currentDir, updateFile)
                    run("mkdir -p %s" % remoteDir)
                    put(currentFile, remoteDir)
                    n += 1

    print(green("total of %s files were updated" % n))

def restartServer():
    print(yellow("restart tomcat"))
    msg = differentEnv()
    stop_tomcat_cmd = msg['stop_tomcat_cmd']
    start_tomcat_cmd = msg['start_tomcat_cmd']
    run(stop_tomcat_cmd)
    time.sleep(10)
    run(start_tomcat_cmd)
@task
def go(updatePackage):
    updateCode(updatePackage)
    restartServer()
